﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xlit.Project.Entity.Domain;
using Xlit.Project.Service;
using Xlit.Standard.Data;

namespace Xlit.Example.Business.Services
{
    /// <summary>
    ///  系统组织
    /// </summary>
    public class SysOrgnizationService : AppServiceBase
    {
        public IRepository<Sys_Orgnization, int> SysOrgnizationRepository { get; set; }

        /// <summary>
        ///  获取组织树
        /// </summary>
        /// <returns></returns>
        public IList<Sys_Orgnization> Get()
        {
            var list = SysOrgnizationRepository.GetList();
            var orgnizationList = list
                .Where(d => !d.ParentId.HasValue)
                .ToList();
            return orgnizationList;
        }

        /// <summary>
        ///  获取组织
        /// </summary>
        /// <param name="id">组织id</param>
        /// <returns></returns>
        public Sys_Orgnization Get(int id)
        {
            var orgnization = SysOrgnizationRepository
                .GetEntity(id);
            return orgnization;
        }

        /// <summary>
        ///  更新组织
        /// </summary>
        /// <param name="input">组织</param>
        /// <returns></returns>
        public int Update(Sys_Orgnization input)
        {
            return SysOrgnizationRepository
               .InsertOrUpdate(input);
        }

        /// <summary>
        ///  删除组织
        ///  有子组织的不能删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(int id)
        {
            if (SysOrgnizationRepository.IsExist(d => d.ParentId == id))
            {
                throw new ApplicationException("此组织下包含子组织, 无法删除");
            }
            return SysOrgnizationRepository.Delete(id);
        }
    }
}
